//! RESP协议解析器单元测试
//! 
//! 测试Redis RESP（Redis Serialization Protocol）协议的解析和生成功能：
//! - 简单字符串解析和生成
//! - 错误信息解析和生成  
//! - 整数解析和生成
//! - 批量字符串解析和生成
//! - 数组解析和生成
//! - 协议错误处理

use redis_rs2::protocol::*;
use crate::common::*;

mod simple_strings_tests {
    use super::*;
    
    #[test]
    fn test_parse_simple_string() {
        // 测试简单字符串解析：+OK\r\n
        let input = b"+OK\r\n";
        
        // 这里需要根据实际的协议解析API进行调整
        let result = TestResult::Success("OK".to_string());
        assert_test_result!(result, "OK".to_string());
    }
    
    #[test]
    fn test_generate_simple_string() {
        // 测试简单字符串生成
        let input = "OK";
        let expected = b"+OK\r\n";
        
        let result = TestResult::Success(expected.to_vec());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_empty_simple_string() {
        // 测试空简单字符串：+\r\n
        let input = b"+\r\n";
        
        let result = TestResult::Success("".to_string());
        assert_test_result!(result, "".to_string());
    }
    
    #[test]
    fn test_parse_simple_string_with_spaces() {
        // 测试包含空格的简单字符串：+Hello World\r\n
        let input = b"+Hello World\r\n";
        
        let result = TestResult::Success("Hello World".to_string());
        assert_test_result!(result, "Hello World".to_string());
    }
}

mod error_strings_tests {
    use super::*;
    
    #[test]
    fn test_parse_error_string() {
        // 测试错误字符串解析：-Error message\r\n
        let input = b"-Error message\r\n";
        
        let result = TestResult::Success("Error message".to_string());
        assert_test_result!(result, "Error message".to_string());
    }
    
    #[test]
    fn test_generate_error_string() {
        // 测试错误字符串生成
        let input = "ERR unknown command";
        let expected = b"-ERR unknown command\r\n";
        
        let result = TestResult::Success(expected.to_vec());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_complex_error() {
        // 测试复杂错误信息：-ERR wrong number of arguments for 'set' command\r\n
        let input = b"-ERR wrong number of arguments for 'set' command\r\n";
        
        let result = TestResult::Success("ERR wrong number of arguments for 'set' command".to_string());
        assert_test_success!(result);
    }
}

mod integers_tests {
    use super::*;
    
    #[test]
    fn test_parse_positive_integer() {
        // 测试正整数解析：:123\r\n
        let input = b":123\r\n";
        
        let result = TestResult::Success(123i64);
        assert_test_result!(result, 123i64);
    }
    
    #[test]
    fn test_parse_negative_integer() {
        // 测试负整数解析：:-123\r\n
        let input = b":-123\r\n";
        
        let result = TestResult::Success(-123i64);
        assert_test_result!(result, -123i64);
    }
    
    #[test]
    fn test_parse_zero_integer() {
        // 测试零值解析：:0\r\n
        let input = b":0\r\n";
        
        let result = TestResult::Success(0i64);
        assert_test_result!(result, 0i64);
    }
    
    #[test]
    fn test_generate_integer() {
        // 测试整数生成
        let input = 42i64;
        let expected = b":42\r\n";
        
        let result = TestResult::Success(expected.to_vec());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_large_integer() {
        // 测试大整数解析
        let input = b":9223372036854775807\r\n"; // i64::MAX
        
        let result = TestResult::Success(9223372036854775807i64);
        assert_test_result!(result, 9223372036854775807i64);
    }
}

mod bulk_strings_tests {
    use super::*;
    
    #[test]
    fn test_parse_bulk_string() {
        // 测试批量字符串解析：$5\r\nhello\r\n
        let input = b"$5\r\nhello\r\n";
        
        let result = TestResult::Success("hello".to_string());
        assert_test_result!(result, "hello".to_string());
    }
    
    #[test]
    fn test_parse_empty_bulk_string() {
        // 测试空批量字符串解析：$0\r\n\r\n
        let input = b"$0\r\n\r\n";
        
        let result = TestResult::Success("".to_string());
        assert_test_result!(result, "".to_string());
    }
    
    #[test]
    fn test_parse_null_bulk_string() {
        // 测试null批量字符串解析：$-1\r\n
        let input = b"$-1\r\n";
        
        let result = TestResult::Success(None::<String>);
        assert!(result.is_success());
    }
    
    #[test]
    fn test_generate_bulk_string() {
        // 测试批量字符串生成
        let input = "hello";
        let expected = b"$5\r\nhello\r\n";
        
        let result = TestResult::Success(expected.to_vec());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_bulk_string_with_binary_data() {
        // 测试包含二进制数据的批量字符串
        let binary_data = vec![0, 1, 2, 3, 255];
        let length = binary_data.len();
        
        // 构造RESP格式：$5\r\n{binary_data}\r\n
        let mut input = format!("${}\r\n", length).into_bytes();
        input.extend_from_slice(&binary_data);
        input.extend_from_slice(b"\r\n");
        
        let result = TestResult::Success(binary_data.clone());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_large_bulk_string() {
        // 测试大批量字符串
        let large_string = generate_random_string(1024 * 10); // 10KB
        let length = large_string.len();
        
        let mut input = format!("${}\r\n", length).into_bytes();
        input.extend_from_slice(large_string.as_bytes());
        input.extend_from_slice(b"\r\n");
        
        let result = TestResult::Success(large_string.clone());
        assert_test_result!(result, large_string);
    }
}

mod arrays_tests {
    use super::*;
    
    #[test]
    fn test_parse_simple_array() {
        // 测试简单数组解析：*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n
        let input = b"*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n";
        
        let expected = vec!["foo".to_string(), "bar".to_string()];
        let result = TestResult::Success(expected.clone());
        assert_test_result!(result, expected);
    }
    
    #[test]
    fn test_parse_empty_array() {
        // 测试空数组解析：*0\r\n
        let input = b"*0\r\n";
        
        let expected: Vec<String> = vec![];
        let result = TestResult::Success(expected.clone());
        assert_test_result!(result, expected);
    }
    
    #[test]
    fn test_parse_null_array() {
        // 测试null数组解析：*-1\r\n
        let input = b"*-1\r\n";
        
        let result = TestResult::Success(None::<Vec<String>>);
        assert!(result.is_success());
    }
    
    #[test]
    fn test_parse_mixed_array() {
        // 测试混合类型数组：*3\r\n:1\r\n+OK\r\n$5\r\nhello\r\n
        let input = b"*3\r\n:1\r\n+OK\r\n$5\r\nhello\r\n";
        
        // 这里需要定义一个可以包含多种类型的结构
        let result = TestResult::Success(vec!["1", "OK", "hello"]);
        assert_test_success!(result);
    }
    
    #[test]
    fn test_generate_array() {
        // 测试数组生成
        let input = vec!["SET".to_string(), "key".to_string(), "value".to_string()];
        let expected = b"*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n";
        
        let result = TestResult::Success(expected.to_vec());
        assert_test_success!(result);
    }
    
    #[test]
    fn test_parse_nested_array() {
        // 测试嵌套数组（如果支持）
        // *2\r\n*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n*1\r\n$3\r\nbaz\r\n
        let input = b"*2\r\n*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n*1\r\n$3\r\nbaz\r\n";
        
        // 这需要支持嵌套数组的数据结构
        let result = TestResult::Success("nested array parsed".to_string());
        assert_test_success!(result);
    }
}

mod protocol_error_handling_tests {
    use super::*;
    
    #[test]
    fn test_invalid_type_prefix() {
        // 测试无效的类型前缀
        let input = b"?invalid\r\n";
        
        let result: TestResult<String> = TestResult::Failure("Invalid type prefix".to_string());
        assert_test_failure!(result);
    }
    
    #[test]
    fn test_missing_crlf() {
        // 测试缺少\r\n的情况
        let input = b"+OK";
        
        let result: TestResult<String> = TestResult::Failure("Missing CRLF".to_string());
        assert_test_failure!(result);
    }
    
    #[test]
    fn test_invalid_length_in_bulk_string() {
        // 测试批量字符串中无效的长度
        let input = b"$abc\r\nhello\r\n";
        
        let result: TestResult<String> = TestResult::Failure("Invalid length".to_string());
        assert_test_failure!(result);
    }
    
    #[test]
    fn test_length_mismatch_in_bulk_string() {
        // 测试批量字符串长度不匹配
        let input = b"$10\r\nhello\r\n"; // 声明长度10但实际只有5
        
        let result: TestResult<String> = TestResult::Failure("Length mismatch".to_string());
        assert_test_failure!(result);
    }
    
    #[test]
    fn test_invalid_array_length() {
        // 测试数组中无效的长度
        let input = b"*abc\r\n";
        
        let result: TestResult<Vec<String>> = TestResult::Failure("Invalid array length".to_string());
        assert_test_failure!(result);
    }
    
    #[test]
    fn test_incomplete_array() {
        // 测试不完整的数组
        let input = b"*2\r\n$3\r\nfoo\r\n"; // 声明2个元素但只有1个
        
        let result: TestResult<Vec<String>> = TestResult::Failure("Incomplete array".to_string());
        assert_test_failure!(result);
    }
}

mod performance_tests {
    use super::*;
    
    #[test]
    fn test_parse_large_array_performance() {
        // 测试解析大数组的性能
        let element_count = 1000;
        let mut input = format!("*{}\r\n", element_count).into_bytes();
        
        for i in 0..element_count {
            let element = format!("element_{}", i);
            input.extend_from_slice(format!("${}\r\n{}\r\n", element.len(), element).as_bytes());
        }
        
        // 测量解析时间
        let start = std::time::Instant::now();
        let result = TestResult::Success(element_count);
        let elapsed = start.elapsed();
        
        assert_test_success!(result);
        // 断言解析时间在合理范围内（比如1秒内）
        assert!(elapsed.as_millis() < 1000, "Parsing took too long: {:?}", elapsed);
    }
    
    #[test]
    fn test_generate_large_response_performance() {
        // 测试生成大响应的性能
        let data = generate_random_string(1024 * 100); // 100KB
        
        let start = std::time::Instant::now();
        let result = TestResult::Success(data.len());
        let elapsed = start.elapsed();
        
        assert_test_success!(result);
        assert!(elapsed.as_millis() < 100, "Generation took too long: {:?}", elapsed);
    }
}

mod edge_cases_tests {
    use super::*;
    
    #[test]
    fn test_maximum_integer_values() {
        // 测试最大整数值
        let max_i64 = i64::MAX;
        let min_i64 = i64::MIN;
        
        let max_input = format!(":{}\r\n", max_i64).into_bytes();
        let min_input = format!(":{}\r\n", min_i64).into_bytes();
        
        let max_result = TestResult::Success(max_i64);
        let min_result = TestResult::Success(min_i64);
        
        assert_test_result!(max_result, max_i64);
        assert_test_result!(min_result, min_i64);
    }
    
    #[test]
    fn test_unicode_in_bulk_string() {
        // 测试批量字符串中的Unicode字符
        let unicode_text = "Hello 世界 🌍";
        let length = unicode_text.as_bytes().len();
        
        let mut input = format!("${}\r\n", length).into_bytes();
        input.extend_from_slice(unicode_text.as_bytes());
        input.extend_from_slice(b"\r\n");
        
        let result = TestResult::Success(unicode_text.to_string());
        assert_test_result!(result, unicode_text.to_string());
    }
    
    #[test]
    fn test_very_long_simple_string() {
        // 测试很长的简单字符串
        let long_string = generate_random_string(1024);
        let input = format!("+{}\r\n", long_string).into_bytes();
        
        let result = TestResult::Success(long_string.clone());
        assert_test_result!(result, long_string);
    }
    
    #[test]
    fn test_zero_length_elements() {
        // 测试零长度元素的处理
        let input = b"*3\r\n$0\r\n\r\n$3\r\nfoo\r\n$0\r\n\r\n";
        
        let expected = vec!["".to_string(), "foo".to_string(), "".to_string()];
        let result = TestResult::Success(expected.clone());
        assert_test_result!(result, expected);
    }
}

// 注意：这些测试目前使用模拟的TestResult
// 实际实现时需要：
// 1. 导入真实的协议解析模块
// 2. 调用实际的解析函数
// 3. 验证真实的解析结果
// 4. 处理实际的解析错误

// 示例真实测试（当协议API就绪时）：
/*
#[test]
fn test_real_resp_parsing() {
    use redis_rs2::protocol::RespParser;
    
    let mut parser = RespParser::new();
    let input = b"+OK\r\n";
    
    let result = parser.parse(input).unwrap();
    match result {
        RespValue::SimpleString(s) => assert_eq!(s, "OK"),
        _ => panic!("Expected SimpleString"),
    }
}
*/